//
//  RecordViewController.m
//  leo
//
//  Created by 常艳 on 15/10/5.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "TaskRecordViewController.h"
#import "LeoMsg.h"
#import "SyncManager.h"
#import "VoiceConverter.h"
@import AVFoundation;
@import AudioToolbox;
@interface TaskRecordViewController ()

@property(nonatomic,strong) AVAudioRecorder *recorder;
@property(nonatomic,strong)    NSString *recordedTmpFile;
@property(nonatomic,strong) NSString *recordFileName;
@property(nonatomic,strong) NSString *amrTmpFile;
@property(nonatomic,strong) NSString *amrFileName;
@property(nonatomic,assign) int startTime;
@property(nonatomic,assign) int endTime;
@property(nonatomic,strong) NSTimer *timer;

@end

@implementation TaskRecordViewController
-(void)dealloc
{
    self.recorder=NULL;
    self.recordedTmpFile=NULL;
    self.recordFileName=NULL;
    [self.timer invalidate];
    self.timer=NULL;
    self.amrTmpFile=NULL;
    self.amrFileName=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.


}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.isCancle=NO;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(int)start
{
    if([self canRecord]==NO)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"无法录音"
                                                        message:@"请在iphone的“设置－隐私－麦克风”选项中，允许应用访问您的手机麦克风"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        alert=nil;
        return -1;
    }
    self.timeLable.hidden=YES;
    NSError *error;

    @try {
        AVAudioSession * audioSession = [AVAudioSession sharedInstance];
        if(audioSession==NULL)
        {
            NSLog(@"%@,start,audioSession is null.",record_tag);
            [LeoMsg showMsg:@"程序发生错误，code is 45"];
            return -1;
        }
        [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
        [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: &error];
        [audioSession setActive:YES error: &error];
        NSString *directoryPath=[[Tooler getDocumentDirectory] stringByAppendingString:@"/record"];
        //文件管理器
        [Tooler isDirectoryExist:directoryPath];
        NSString *ts=[Tooler getTS];
        self.recordFileName=[NSString stringWithFormat: @"%@.%@", ts, @"wav"];
        self.recordedTmpFile =[directoryPath stringByAppendingString:[NSString stringWithFormat:@"/%@",self.recordFileName]];
        self.amrFileName=[NSString stringWithFormat: @"%@.%@", ts, @"amr"];
        self.amrTmpFile=[directoryPath stringByAppendingString:[NSString stringWithFormat:@"/%@",self.amrFileName]];
        //NSLog(@"Using File called: %@",self.recordedTmpFile);
        //NSMutableDictionary* recordSetting = [[NSMutableDictionary alloc] init];
        //[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];

        /*
        NSMutableDictionary* recordSetting = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                              [NSNumber numberWithInt:kAudioFormatMPEG4AAC], AVFormatIDKey,
                                              [NSNumber numberWithFloat:16000.0], AVSampleRateKey,
                                              [NSNumber numberWithInt:1], AVNumberOfChannelsKey,
                                              [NSNumber numberWithInt:AVAudioQualityMin], AVEncoderAudioQualityKey,
                                              [NSNumber numberWithInt:AVAudioQualityMin], AVSampleRateConverterAudioQualityKey,
                                              [NSNumber numberWithInt:8], AVLinearPCMBitDepthKey,
                                              nil];*/
        
        NSDictionary *recordSetting=[VoiceConverter GetAudioRecorderSettingDict];
        self.recorder = [[ AVAudioRecorder alloc] initWithURL:[NSURL URLWithString:self.recordedTmpFile] settings:recordSetting error:&error];
        if(error!=nil)
        {
            NSLog(@"%@,start,create record error, error is %@.",record_tag,error);
            return -1;
        }
        self.recorder.meteringEnabled=YES;
        [self.recorder setDelegate:self];
        [self.recorder prepareToRecord];
        self.startTime=[self.recorder deviceCurrentTime];
        [self.recorder record];
        self.actionImg.image=[UIImage imageNamed:@"record_anim0@2x"];
        self.timer=[NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(timeCounter) userInfo:nil repeats:YES];
    }
    @catch (NSException *exception) {
        NSLog(@"%@,start, exception is %@",record_tag,exception.reason);
    }
    return 1;

}
-(void)timeCounter
{
    self.endTime=[self.recorder deviceCurrentTime];
    int time=self.endTime-self.startTime;
    if(time>=10)
    {
        self.timeLable.hidden=NO;
        self.timeLable.text=[NSString stringWithFormat:@"还可以说%d秒",(20-time)];
    }
    if(time>=20)
    {
        [self stop];
        [[NSNotificationCenter defaultCenter] postNotificationName:RECORDTIMEEXCEED object:nil userInfo:nil];
    }
    if(!self.isCancle)
    {
        [self updatePowerMeters];
    }
}
-(void)updatePowerMeters
{
    [self.recorder updateMeters];
    
    float averagePower = [self.recorder averagePowerForChannel:0];
    if(averagePower<-60)
    {
        self.actionImg.image=[UIImage imageNamed:@"record_anim0@2x"];
    }
    else if(averagePower<-50)
    {
        self.actionImg.image=[UIImage imageNamed:@"record_anim1@2x"];
    }
    else if(averagePower<-45)
    {
        self.actionImg.image=[UIImage imageNamed:@"record_anim1@2x"];
    }
    else if(averagePower<-40)
    {
        self.actionImg.image=[UIImage imageNamed:@"record_anim2@2x"];
    }
    else if(averagePower<-35)
    {
        self.actionImg.image=[UIImage imageNamed:@"record_anim3@2x"];
    }
    else if(averagePower<-30)
    {
        self.actionImg.image=[UIImage imageNamed:@"record_anim4@2x"];
    }
    else if(averagePower<-25)
    {
        self.actionImg.image=[UIImage imageNamed:@"record_anim5@2x"];
    }
    else if(averagePower<-20)
    {
        self.actionImg.image=[UIImage imageNamed:@"record_anim6@2x"];
    }
    else if(averagePower<-15)
    {
        self.actionImg.image=[UIImage imageNamed:@"record_anim7@2x"];
    }
    else if(averagePower<-10)
    {
        self.actionImg.image=[UIImage imageNamed:@"record_anim8@2x"];
    }
    else if(averagePower<-5)
    {
        self.actionImg.image=[UIImage imageNamed:@"record_anim10@2x"];
    }
    else if(averagePower<=0)
    {
        self.actionImg.image=[UIImage imageNamed:@"record_anim10@2x"];
    }

}
-(void)stop//停止录制，并保存录音文件
{
    if(self.timer!=NULL)
    {
        [self.timer invalidate];
        self.timer=NULL;
    }
    if(self.recorder==NULL)
    {
        NSLog(@"%@,stop,recorder is null.",record_tag);
        return ;
    }
    self.endTime=[self.recorder deviceCurrentTime];
    [self.recorder stop];
    self.recorder=NULL;    
    if(self.endTime-self.startTime<1)
    {
        return ;
    }
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断数据库是否存在
    BOOL find = [fileManager fileExistsAtPath:[NSString stringWithFormat:@"%@",self.recordedTmpFile]];
    if(!find)
    {
        NSLog(@"%@,stop,save the record file error.",record_tag);
        self.recordedTmpFile=NULL;
    }
 
}
-(NSString *)getAudioUrl
{
    if(self.recordFileName!=NULL)
        return [NSString stringWithFormat:@"/record/%@",self.recordFileName];
    return self.recordFileName;
    
}
-(NSString *)getRecordSaveUrl
{
   return self.recordedTmpFile;
}
-(NSString *)getAmrUrl
{
    if(self.amrFileName!=NULL)
        return [NSString stringWithFormat:@"/record/%@",self.amrFileName];
    else
        return self.amrFileName;
}
-(NSString *)getAmrSaveUrl
{
    return self.amrTmpFile;
}
-(int)getDuration
{
    return self.endTime-self.startTime;
}

-(BOOL)canRecord

{
    __block BOOL bCanRecord = YES;
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                if (granted) {
                    bCanRecord = YES;
                }
                else {
                    bCanRecord = NO;
                }
            }];
        }
    }
    
    return bCanRecord;
}
@end
